package com.example.multiplesprite;

import java.util.Random;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect; 

public class Character {
       int[] DIRECTION_TO_ANIMATION_MAP = { 3, 1, 0, 2 };
       private static final int CHAR_ROWS = 4;
       private static final int CHAR_COLUMNS = 3;
       private static final int MAX_SPEED = 5;
       private GameController GameController;
       private Bitmap _characterbmp;
       private int _xPos = 0;
       private int _yPos = 0;
       private int _xVelocity;
       private int _yVelocity;
       private int _currentFrame = 0;
       private int _width;
       private int _height; 

       public Character(GameController GameController, Bitmap _characterbmp) {
             this._width = _characterbmp.getWidth() / CHAR_COLUMNS;
             this._height = _characterbmp.getHeight() / CHAR_ROWS;
             this.GameController = GameController;
             this._characterbmp = _characterbmp;
             Random _randomValue = new Random();
             _xPos = _randomValue.nextInt(GameController.getWidth() - _width);
             _yPos = _randomValue.nextInt(GameController.getHeight() - _height);
             _xVelocity = _randomValue.nextInt(MAX_SPEED * 2) - MAX_SPEED;
             _yVelocity = _randomValue.nextInt(MAX_SPEED * 2) - MAX_SPEED;
       }

       private void update() {
             if (_xPos >= GameController.getWidth() - _width - _xVelocity || _xPos + _xVelocity <= 0) {
                    _xVelocity = -_xVelocity;
             }
             _xPos = _xPos + _xVelocity;
             if (_yPos >= GameController.getHeight() - _height - _yVelocity || _yPos + _yVelocity <= 0) {
                    _yVelocity = -_yVelocity;
             }
             _yPos = _yPos + _yVelocity;
             _currentFrame = ++_currentFrame % CHAR_COLUMNS;
       }

       public void onDraw(Canvas canvas) {
             update();
             int orgX = _currentFrame * _width;
             int orgY = getAnimationRow() * _height;
             Rect src = new Rect(orgX, orgY, orgX + _width, orgY + _height);
             Rect dst = new Rect(_xPos, _yPos, _xPos + _width, _yPos + _height);
             canvas.drawBitmap(_characterbmp, src, dst, null);
       } 

       private int getAnimationRow() {
             double dirDouble = (Math.atan2(_xVelocity, _yVelocity) / (Math.PI / 2) + 2);
             int direction = (int) Math.round(dirDouble) % CHAR_ROWS;
             return DIRECTION_TO_ANIMATION_MAP[direction];
       }

}